<?php
/*
 * 集成阿里云通信轻量级短信接口
 *
 * 2018/07/13
 */

namespace app\common\model;

use think\Exception;
use think\Model;

class Jhsms extends Model
{
    //设置信息
    private $settings = [];

    public function __construct()
    {
        $this->settings = config('jhsms');
    }

    /**
     * @param string $mobile 手机号
     * @param int $type 验证码类型 1 注册验证码 2 找回密码 3 用户登录
     **/
    public function send_sms($mobile, $type)
    {
        if ($type == 2 || $type == 3) {
            if (!User::exists($mobile)) {
                throw new Exception("你还未注册，注册后登录");
            }
        }
        if ($type == 1) {
            if (User::exists($mobile)) {
                throw new Exception("你已注册，可以直接登录");
            }
        }
        //生成验证码
        $captcha = self::generateCaptcha($mobile, $type);
        //记录验证码记录
        $insertId = db("sms_log")->insertGetId([
            "telephone" => $mobile,
            "vcode" => $captcha,
            "exp_time" => time() + 600,
            "type" => $type,
            "create_time" => time()
        ]);
        if (!$insertId) {
            throw new Exception("验证码发送异常");
        }
        $sendUrl = $this->settings['send_url']; //短信接口的URL
        $smsConf = array(
            'key' => $this->settings['app_key'], //您申请的APPKEY
            'mobile' => $mobile, //接受短信的用户手机号码
            'tpl_id' => $this->settings['template_id'], //您申请的短信模板ID，根据实际情况修改
            'tpl_value' => '#code#=' . $captcha //您设置的模板变量，根据实际情况修改
        );
//        $content = $this->juhecurl($sendUrl, $smsConf, 1); //请求发送短信
        $content = json_encode(["error_code"=>0]); //请求发送短信
        if ($content) {
            $result = json_decode($content, true);
            $error_code = $result['error_code'];
            if ($error_code == 0) {
                //存储短信验证码
                db("sms_log")->where("id", $insertId)->update(['status' => 1]);
            } else {
                //状态非0，说明失败
                $msg_r = $result['reason'];
                db("sms_log")->where("id", $insertId)->update(["status" => -1, "remarks" => $msg_r]);
                throw new DeveloperException("短信发送失败(" . $error_code . ")：" . $msg_r);
            }
        } else {
            //返回内容异常，以下可根据业务逻辑自行修改
            db("sms_log")->where("id", $insertId)->update(["status" => -1, "remarks" => "系统异常"]);
            throw new DeveloperException('请求发送短信失败');
        }
    }

    /**
     * 获取验证码
     * @param $mobile
     * @param $type
     * @return string
     * @throws UserException
     */
    static public function generateCaptcha($mobile, $type)
    {
        $code_res = self::getVcode($mobile, $type);
        if (!$code_res) {
            //生成验证码
            return random(6, true);
        }
        if ($code_res["exp_time"] < time()) {
            //验证码已过期标记已过期
            db("sms_log")->where("id", $code_res["id"])->update(["status" => 3]);
            return random(6, true);
        } else {
            throw new UserException("验证码有效期为10分钟,请查看手机短信!");
        }
    }

    /**
     * 获取验证码记录
     * @param $mobile
     * @param $type
     */
    public static function getVcode($mobile, $type)
    {
        $res = db("sms_log")->where("telephone", $mobile)->where("type", $type)->where("status", 1)->find();
        return $res;
    }

    public static function verifyCaptcha($mobile, $captcha, $type)
    {
        $res = db("sms_log")->where("telephone", $mobile)->where("type", $type)->where("vcode", $captcha)->find();
        if (empty($res)) {
            throw new Exception("验证码错误");
        }
        if ($res["status"] != 1 || $res["exp_time"] < time()) {
            throw new Exception("验证码已过期");
        }
        db("sms_log")->where("id", $res["id"])->update(["status"=>2]);
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    private function juhecurl($url, $params = false, $ispost = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

}
